import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Navbar from '@/components/Navbar';
import SearchBar from '@/components/SearchBar';
import Carousel from '@/components/Carousel';
import LoginModal from '@/components/LoginModal';
import './Home.css';

interface GroupedSuggestion {
  group: string;
  items: string[];
}

interface CreativeTool {
  title: string;
  desc: string;
  icon?: string;
  img?: string;
  bg: string;
}

// 定义卡片数据接口
interface CardData {
  title: string;
  desc?: string;
  tag?: string;
  color?: string;
}

// 通用TabsWithPages组件
function TabsWithPages({ tabs, data, pageSize = 4 }: { 
  tabs: string[]; 
  data: Record<string, CardData[]>; 
  pageSize?: number; 
}) {
  const [activeTab, setActiveTab] = useState(tabs[0]);
  const [page, setPage] = useState(0);
  const cards = data[activeTab] || [];
  const totalPages = Math.ceil(cards.length / pageSize);
  const currentPageCards = cards.slice(page * pageSize, (page + 1) * pageSize);
  const handleTabClick = (tab: string) => {
    setActiveTab(tab);
    setPage(0);
  };
  return (
    <div style={{ width: '100%' }}>
      {/* Tab栏 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 32, marginBottom: 18 }}>
        {tabs.map((tab: string) => (
          <span
            key={tab}
            style={{
              fontWeight: tab === activeTab ? 700 : 500,
              fontSize: 20,
              color: tab === activeTab ? '#222' : '#888',
              cursor: 'pointer',
              borderBottom: tab === activeTab ? '2.5px solid #222' : 'none',
              paddingBottom: 4
            }}
            onClick={() => handleTabClick(tab)}
          >
            {tab}
          </span>
        ))}
      </div>
      {/* 内容区左右翻页 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {/* 左翻页按钮 */}
        <button
          onClick={() => setPage(p => Math.max(0, p - 1))}
          disabled={page === 0}
          style={{
            width: 32, height: 32, borderRadius: 16, border: 'none', background: '#f0f0f0', color: '#888', fontSize: 20, cursor: page === 0 ? 'not-allowed' : 'pointer', marginRight: 8
          }}
        >&lt;</button>
        {/* 当前页卡片 */}
        <div style={{ display: 'flex', gap: 18, flex: 1, overflow: 'hidden' }}>
          {currentPageCards.map((card: CardData) => (
            <div key={card.title} style={{
              flex: '0 0 200px',
              background: '#fff',
              borderRadius: 14,
              boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
              padding: '12px 12px 10px 12px',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-start',
              minHeight: 180,
              cursor: 'pointer',
              border: '1px solid #e3eaf1',
              position: 'relative',
              transition: 'box-shadow 0.2s',
              gap: 8
            }}>
              {card.tag && <div style={{ color: '#ff4d4f', fontWeight: 700, fontSize: 15, marginBottom: 6 }}>{card.tag} <span style={{ color: '#ff4d4f', fontWeight: 400, fontSize: 16 }}>&gt;</span></div>}
              <div style={{
                width: '100%',
                height: 90,
                background: card.color || '#f5f5f5',
                borderRadius: 8,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 8,
                fontSize: 38,
                color: '#222',
                fontWeight: 500
              }}>{card.title}</div>
              <div style={{ fontWeight: 600, fontSize: 16, color: '#222', marginBottom: 2 }}>{card.title}</div>
              {card.desc && <div style={{ color: '#b0b8c4', fontSize: 13 }}>{card.desc}</div>}
            </div>
          ))}
        </div>
        {/* 右翻页按钮 */}
        <button
          onClick={() => setPage(p => Math.min(totalPages - 1, p + 1))}
          disabled={page >= totalPages - 1}
          style={{
            width: 32, height: 32, borderRadius: 16, border: 'none', background: '#f0f0f0', color: '#888', fontSize: 20, cursor: page >= totalPages - 1 ? 'not-allowed' : 'pointer', marginLeft: 8
          }}
        >&gt;</button>
      </div>
    </div>
  );
}

// 恢复 CreativeToolCard 组件到之前的版本
const CreativeToolCard = ({ tool }: { tool: CreativeTool }) => {

  const navigate = useNavigate();

  const [hover, setHover] = useState(false);
  const isCreate = tool.title === '创建设计';
  const isAI = tool.title === 'AI设计';
  const isImageEdit = tool.title === '图片编辑';

  const isAIMatting = tool.title === 'AI抠图';

  // 通用卡片基础样式
  const baseStyle: React.CSSProperties = {
    flex: '0 0 170px',
    width: 170,
    borderRadius: 14,
    boxShadow: hover ? '0 8px 32px rgba(124,92,255,0.12)' : '0 2px 8px rgba(0,0,0,0.06)',
    padding: '28px 18px 20px 18px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    border: hover ? '1.5px solid #7c5cff' : '1px solid #e3eaf1',
    position: 'relative',
    transition: 'all 0.3s cubic-bezier(.4,2,.6,1)',
    gap: 8,
    overflow: 'hidden',
    transform: hover ? 'translateY(-6px) scale(1.04)' : 'none',
    minHeight: isCreate || isAI || isImageEdit || isAIMatting ? 200 : 90,
    height: isCreate || isAI || isImageEdit || isAIMatting ? 200 : 90,
    background: isCreate || isAI || isImageEdit || isAIMatting ? 'linear-gradient(135deg, #f5f8ff 60%, #f7f7ff 100%)' : tool.bg,
  };

  if (isCreate) {
    return (
      <div
        style={baseStyle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
      >
        {/* 默认内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 0 : 1,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <span style={{ fontSize: 32, color: '#7c5cff', margin: 0 }}>+</span>
          <div style={{ fontWeight: 700, fontSize: 20, color: '#222', margin: 0, textAlign: 'center' }}>创建设计</div>
          <div style={{ color: '#b0b8c4', fontSize: 15, margin: 0, textAlign: 'center' }}>开始你的创意</div>
        </div>
        {/* 悬浮内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 1 : 0,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', display: 'flex', alignItems: 'center', gap: 4 }}>
            创建设计 <span style={{ fontSize: 18, color: '#7c5cff' }}>{'>'}</span>
          </div>
          <img src="https://dummyimage.com/60x40/7c5cff/fff&text=+" alt="" style={{ width: 60, height: 40, borderRadius: 8, objectFit: 'cover' }} />
        </div>
      </div>
    );
  }
  if (isAI) {
    return (
      <div
        style={baseStyle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
      >
        {/* 默认内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 0 : 1,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <span style={{ fontSize: 38, color: '#7c5cff', margin: 0 }}>✨</span>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', margin: 0, textAlign: 'center' }}>AI设计</div>
          <div style={{ color: '#b0b8c4', fontSize: 14, textAlign: 'center', margin: 0 }}>探索创造极限</div>
        </div>
        {/* 悬浮内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 1 : 0,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', display: 'flex', alignItems: 'center', gap: 4 }}>
            AI设计 <span style={{ fontSize: 18, color: '#7c5cff' }}>{'>'}</span>
          </div>
          <img src="https://img1.baidu.com/it/u=1814302747,3704489962&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256" alt="" style={{ width: 60, height: 40, borderRadius: 8, objectFit: 'cover' }} />
        </div>
      </div>
    );
  }
  if (isImageEdit) {
    return (
      <div
        style={baseStyle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
      >
        {/* 默认内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 0 : 1,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <span style={{ fontSize: 38, color: '#ff7c5c', margin: 0 }}>✏️</span>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', margin: 0, textAlign: 'center' }}>图片编辑</div>
          <div style={{ color: '#b0b8c4', fontSize: 14, textAlign: 'center', margin: 0 }}>全能图片处理工具</div>
        </div>
        {/* 悬浮内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 1 : 0,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', display: 'flex', alignItems: 'center', gap: 4 }}>
            图片编辑 <span style={{ fontSize: 18, color: '#7c5cff' }}>{'>'}</span>
          </div>
          <img src="https://img2.baidu.com/it/u=2062345332,2462621062&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256" alt="" style={{ width: 60, height: 40, borderRadius: 8, objectFit: 'cover' }} />
        </div>
      </div>
    );
  }
  if (isAIMatting) {
    return (
      <div
        style={baseStyle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        onClick={() => navigate('/ai')}
      >
        {/* 默认内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 0 : 1,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <span style={{ fontSize: 38, color: '#667eea', margin: 0 }}>🖼️</span>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', margin: 0, textAlign: 'center' }}>AI抠图</div>
          <div style={{ color: '#b0b8c4', fontSize: 14, textAlign: 'center', margin: 0 }}>智能抠图工具</div>
        </div>
        {/* 悬浮内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 1 : 0,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <div style={{ fontWeight: 500, fontSize: 18, color: '#222', display: 'flex', alignItems: 'center', gap: 4 }}>
            AI抠图 <span style={{ fontSize: 18, color: '#7c5cff' }}>{'>'}</span>
          </div>
          <img src="https://img1.baidu.com/it/u=1814302747,3704489962&fm=253&fmt=auto&app=138&f=JPEG?w=256&h=256" alt="" style={{ width: 60, height: 40, borderRadius: 8, objectFit: 'cover' }} />
        </div>
      </div>
    );
  }
  // 其它小卡片内容切换动画
  if (!isCreate && !isAI && !isImageEdit && !isAIMatting) {
    return (
      <div
        style={baseStyle}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
      >
        {/* 默认内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 0 : 1,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <span style={{ fontSize: 22, color: '#7c5cff', margin: 0 }}>{tool.icon || '...'}</span>
          <div style={{ fontWeight: 600, fontSize: 15, margin: 0 }}>{tool.title}</div>
        </div>
        {/* 悬浮内容 */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          height: '100%',
          transition: 'opacity 0.3s cubic-bezier(.4,2,.6,1)',
          opacity: hover ? 1 : 0,
          pointerEvents: hover ? 'auto' : 'none',
          zIndex: hover ? 2 : 1,
        }}>
          <div style={{ fontWeight: 700, fontSize: 16, color: '#222', display: 'flex', alignItems: 'center', gap: 4 }}>
            {tool.title}
          </div>
          <span style={{ fontSize: 18, color: '#7c5cff' }}>{'>'}</span>
        </div>
      </div>
    );
  }

  return (
    <div style={baseStyle} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
      {isAI ? (
        <>
          <span style={{ fontSize: 38, color: '#7c5cff', margin: 0 }}>✨</span>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', margin: 0, textAlign: 'center' }}>AI设计</div>
          <div style={{ color: '#b0b8c4', fontSize: 14, textAlign: 'center', margin: 0 }}>探索创造极限</div>
        </>
      ) : isImageEdit ? (
        <>
          <span style={{ fontSize: 38, color: '#ff7c5c', margin: 0 }}>✏️</span>
          <div style={{ fontWeight: 700, fontSize: 18, color: '#222', margin: 0, textAlign: 'center' }}>图片编辑</div>
          <div style={{ color: '#b0b8c4', fontSize: 14, textAlign: 'center', margin: 0 }}>全能图片处理工具</div>
        </>
      ) : (
        <>
          <span style={{ fontSize: 22, color: '#7c5cff', margin: 0 }}>{tool.icon || '...'}</span>
          <div style={{ fontWeight: 600, fontSize: 15, margin: 0 }}>{tool.title}</div>
          {tool.desc && <div style={{ color: '#b0b8c4', fontSize: 13, whiteSpace: 'nowrap', margin: 0 }}>{tool.desc}</div>}
        </>
      )}
    </div>
  );
};

function Index() {
  // 所有useState声明放在useEffect之前
  const [isLoginModalOpen, setIsLoginModalOpen] = useState(false);
  const searchBarRef = useRef<HTMLDivElement>(null); // 新增ref
  const [popStyle, setPopStyle] = useState<{ left: number; top: number; width: number } | null>(null);
  const [inputValue, setInputValue] = useState('');
  const [showSearchPopup, setShowSearchPopup] = useState(false);
  const [groupedSuggestionsState, setGroupedSuggestionsState] = useState<GroupedSuggestion[]>([]);

  // 轮播图数据 - 简洁的文本内容
  const carouselItems = [
    {
      id: '1',
      title: 'Slide 1',
      description: '创意设计，无限可能'
    },
    {
      id: '2',
      title: 'Slide 2',
      description: 'AI驱动，智能设计'
    },
    {
      id: '3',
      title: 'Slide 3',
      description: '专业模板，一键生成'
    },
    {
      id: '4',
      title: 'Slide 4',
      description: '品牌营销，效果显著'
    }
  ];

  const handleSearch = (keyword: string) => {
    console.log('搜索关键词:', keyword);
    // 这里可以添加搜索逻辑
  };

  const handleLoginClick = () => {
    setIsLoginModalOpen(true);
  };

  const handleCloseLoginModal = () => {
    setIsLoginModalOpen(false);
  };

  // 定位弹窗到搜索框下方
  useEffect(() => {
    if (showSearchPopup && searchBarRef.current) {
      const rect = searchBarRef.current.getBoundingClientRect();
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
      setPopStyle({
        left: rect.left + scrollLeft,
        top: rect.bottom + scrollTop + 2,
        width: rect.width,
      });
    }
  }, [showSearchPopup]);

  useEffect(() => {
    if (!showSearchPopup) return;
    function handleClick(e: MouseEvent) {
      if (searchBarRef.current && !searchBarRef.current.contains(e.target as Node)) {
        setShowSearchPopup(false);
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showSearchPopup]);



  // 热门推荐内容（每行一组，左右两列）
  const hotSearchRows = [
    {
      left: { title: '端午', hot: true, img: 'https://dummyimage.com/80x110/fff6f6/333&text=端午', bg: 'linear-gradient(90deg,#fff6f6 60%,#fff 100%)' },
      right: { title: '文章长图', img: 'https://dummyimage.com/80x110/fff/333&text=文章长图' }
    },
    {
      left: { title: '六一', hot: true, img: 'https://dummyimage.com/80x110/fff6f6/333&text=六一', bg: 'linear-gradient(90deg,#fff6f6 60%,#fff 100%)' },
      right: { title: '长图', img: 'https://dummyimage.com/80x110/fff/333&text=长图' }
    },
    {
      left: { title: '表格', img: 'https://dummyimage.com/80x110/fffbe6/333&text=表格', bg: 'linear-gradient(90deg,#fffbe6 60%,#fff 100%)' },
      right: { title: '高考', hot: true, img: 'https://dummyimage.com/80x110/fff/333&text=高考' }
    },
    {
      left: { title: '小红书配图', img: 'https://dummyimage.com/80x110/f6fff6/333&text=小红书', bg: 'linear-gradient(90deg,#f6fff6 60%,#fff 100%)' },
      right: { title: '气泡', img: 'https://dummyimage.com/80x110/fff/333&text=气泡' }
    },
    {
      left: { title: '边框', img: 'https://dummyimage.com/80x110/eff6ff/333&text=边框', bg: 'linear-gradient(90deg,#eff6ff 60%,#fff 100%)' },
      right: { title: '龙舟', img: 'https://dummyimage.com/80x110/fff/333&text=龙舟' }
    }
  ];

  // 本地静态建议词
  const groupedSuggestions = [
    {
      group: 'Q搜索建议',
      items: ['Q 六一海报', 'Q 六一活动', 'Q 六一通知', 'Q 六一系列', 'Q 六一设计', '端午', '你好', '文章', '端午节', '你好世界', '文章长图']
    },
    {
      group: '按工具搜索',
      items: ['按工具搜索"六一"', '按工具搜索"端午"', '按工具搜索"你好"', '按工具搜索"文章"']
    },
    {
      group: 'AI电商素材',
      items: ['AI六一素材', '六一设计素材', 'AI端午素材', 'AI你好素材', 'AI文章素材']
    }
  ];

  // 传递给SearchBar的输入变化和联想回调
  const handleInputChange = async (value: string) => {
    setInputValue(value);
    if (value) {
      const suggestions = await fetchGroupedSuggestions(value);
      setGroupedSuggestionsState(suggestions);
    } else {
      setGroupedSuggestionsState([]);
    }
  };

  // SearchBar异步获取分组建议后回调
  const fetchGroupedSuggestions = async (value: string): Promise<GroupedSuggestion[]> => {
    return new Promise(resolve => {
      setTimeout(() => {
        if (!value) {
          resolve([]);
          return;
        }
        const result = groupedSuggestions
          .map(g => ({
            group: g.group,
            items: g.items.filter(item => item.toLowerCase().includes(value.toLowerCase())),
          }))
          .filter(g => g.items.length > 0);
        resolve(result);
      }, 300);
    });
  };

  // 创作工具卡片数据
  const creativeTools: CreativeTool[] = [
    { title: '创建设计', desc: '开始你的创意', icon: '+', bg: '#f5f8ff' },
    { title: 'AI设计', desc: '探索创造极限', icon: '✨', bg: '#fff' },
    { title: '图片编辑', desc: '全能图片处理工具', icon: '✏️', bg: '#fff' },
    { title: 'AI抠图', desc: '', icon: '🖼️', bg: '#fff' },
    { title: 'AI绘图', desc: '', icon: '🎨', bg: '#fff' },
    { title: '拼图', desc: '', icon: '📄', bg: '#fff' },
    { title: 'AI消除', desc: '', icon: '💥', bg: '#fff' },
    { title: 'H5页面制作', desc: 'H5页面制作', icon: 'H5', bg: '#fff' },
    { title: 'AI变清晰', desc: '', icon: '✨', bg: '#fff' },
    { title: '尺寸延展', desc: '', icon: '📏', bg: '#fff' },
    { title: '更多创作工具', desc: '', icon: '🌈', bg: '#fff' }
  ];

  // 小红书Tab和内容数据
  const xhsTabs = ['小红书', '电商', '公众号', '教育培训', '零售', '生活日常', '行政办公'];
  const xhsTabCards = {
    '小红书': [
      { tag: '爆款人气榜', title: '爆款', desc: '爆款人气榜', img: '', color: '#ffeaea' },
      { tag: '行业更新榜', title: '行业', desc: '行业更新榜', img: '', color: '#fff6e1' },
      { tag: '作图飙升榜', title: '升', desc: '作图飙升榜', img: '', color: '#eaf6ff' },
      { tag: '', title: '大字', desc: 'AI大字封面', img: '', color: '#eaf6ff' },
      { tag: '新品推荐', title: '新品', desc: '新品推荐榜', img: '', color: '#eaffea' },
      { tag: '达人推荐', title: '达人', desc: '达人推荐榜', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '电商': [
      { tag: '热卖榜', title: '热卖', desc: '热卖商品榜', img: '', color: '#ffeaea' },
      { tag: '新品榜', title: '新品', desc: '新品上架榜', img: '', color: '#fff6e1' },
      { tag: '爆单榜', title: '爆单', desc: '爆单推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大促', desc: '大促活动', img: '', color: '#eaf6ff' },
      { tag: '品牌榜', title: '品牌', desc: '品牌推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '公众号': [
      { tag: '爆文榜', title: '爆文', desc: '爆文推荐', img: '', color: '#ffeaea' },
      { tag: '行业榜', title: '行业', desc: '行业推荐', img: '', color: '#fff6e1' },
      { tag: '涨粉榜', title: '涨粉', desc: '涨粉推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大字', desc: '大字封面', img: '', color: '#eaf6ff' },
      { tag: '新品榜', title: '新品', desc: '新品推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '教育培训': [
      { tag: '课程榜', title: '课程', desc: '热门课程', img: '', color: '#ffeaea' },
      { tag: '行业榜', title: '行业', desc: '行业推荐', img: '', color: '#fff6e1' },
      { tag: '涨粉榜', title: '涨粉', desc: '涨粉推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大字', desc: '大字封面', img: '', color: '#eaf6ff' },
      { tag: '新品榜', title: '新品', desc: '新品推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '零售': [
      { tag: '热卖榜', title: '热卖', desc: '热卖商品榜', img: '', color: '#ffeaea' },
      { tag: '新品榜', title: '新品', desc: '新品上架榜', img: '', color: '#fff6e1' },
      { tag: '爆单榜', title: '爆单', desc: '爆单推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大促', desc: '大促活动', img: '', color: '#eaf6ff' },
      { tag: '品牌榜', title: '品牌', desc: '品牌推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '生活日常': [
      { tag: '生活榜', title: '生活', desc: '生活推荐', img: '', color: '#ffeaea' },
      { tag: '行业榜', title: '行业', desc: '行业推荐', img: '', color: '#fff6e1' },
      { tag: '涨粉榜', title: '涨粉', desc: '涨粉推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大字', desc: '大字封面', img: '', color: '#eaf6ff' },
      { tag: '新品榜', title: '新品', desc: '新品推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
    '行政办公': [
      { tag: '办公榜', title: '办公', desc: '办公推荐', img: '', color: '#ffeaea' },
      { tag: '行业榜', title: '行业', desc: '行业推荐', img: '', color: '#fff6e1' },
      { tag: '涨粉榜', title: '涨粉', desc: '涨粉推荐', img: '', color: '#eaf6ff' },
      { tag: '', title: '大字', desc: '大字封面', img: '', color: '#eaf6ff' },
      { tag: '新品榜', title: '新品', desc: '新品推荐', img: '', color: '#eaffea' },
      { tag: '达人榜', title: '达人', desc: '达人推荐', img: '', color: '#f0eaff' },
      { tag: '热搜榜', title: '热搜', desc: '热搜榜单', img: '', color: '#eafff6' },
      { tag: '优选榜', title: '优选', desc: '优选榜单', img: '', color: '#fffbe1' },
    ],
  };

  // 推荐区卡片数据（增加图片，保证可翻页）
  const newRecommendList = [
    { id: 1, title: '梦想晨曦', img: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=300&q=80' },
    { id: 2, title: '山海皆可平', img: 'https://images.unsplash.com/photo-1502082553048-f009c37129b9?auto=format&fit=crop&w=300&q=80' },
    { id: 3, title: '大美', img: 'https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?auto=format&fit=crop&w=300&q=80' },
    { id: 4, title: '牙齿健康', img: 'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?auto=format&fit=crop&w=300&q=80' },
    { id: 5, title: '你好早安', img: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=300&q=80' },
    { id: 6, title: 'AI新境', img: 'https://images.unsplash.com/photo-1465101178521-c1a9136a3fd9?auto=format&fit=crop&w=300&q=80' },
    { id: 7, title: '古诗词鉴赏', img: 'https://images.unsplash.com/photo-1467269204594-9661b134dd2b?auto=format&fit=crop&w=300&q=80' },
    { id: 8, title: '初伏', img: 'https://images.unsplash.com/photo-1501785888041-af3ef285b470?auto=format&fit=crop&w=300&q=80' },
    { id: 9, title: '大暑', img: 'https://images.unsplash.com/photo-1519864600265-abb23847ef2c?auto=format&fit=crop&w=300&q=80' },
    { id: 10, title: '夏日沙滩', img: 'https://images.unsplash.com/photo-1502082553048-f009c37129b9?auto=format&fit=crop&w=300&q=80' },
    { id: 11, title: '清晨海岸', img: 'https://images.unsplash.com/photo-1467269204594-9661b134dd2b?auto=format&fit=crop&w=300&q=80' },
    { id: 12, title: '绿意盎然', img: 'https://images.unsplash.com/photo-1501785888041-af3ef285b470?auto=format&fit=crop&w=300&q=80' },
  ];
  const hotRecommendList = [
    { id: 1, title: '情绪太上头如何解决', img: 'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?auto=format&fit=crop&w=300&q=80' },
    { id: 2, title: '清楚事业编考试', img: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=300&q=80' },
    { id: 3, title: '理性讨论', img: 'https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?auto=format&fit=crop&w=300&q=80' },
    { id: 4, title: '30岁女生建议', img: 'https://images.unsplash.com/photo-1504674900247-0877df9cc836?auto=format&fit=crop&w=300&q=80' },
    { id: 5, title: '苹果10斤现摘', img: 'https://images.unsplash.com/photo-1502741338009-cac2772e18bc?auto=format&fit=crop&w=300&q=80' },
    { id: 6, title: '全面营养', img: 'https://images.unsplash.com/photo-1515378791036-0648a3ef77b2?auto=format&fit=crop&w=300&q=80' },
    { id: 7, title: '健康生活', img: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?auto=format&fit=crop&w=300&q=80' },
    { id: 8, title: '美味甜品', img: 'https://images.unsplash.com/photo-1519864600265-abb23847ef2c?auto=format&fit=crop&w=300&q=80' },
    { id: 9, title: '运动健身', img: 'https://images.unsplash.com/photo-1465101178521-c1a9136a3fd9?auto=format&fit=crop&w=300&q=80' },
    { id: 10, title: '艺术创意', img: 'https://images.unsplash.com/photo-1464983953574-0892a716854b?auto=format&fit=crop&w=300&q=80' },
  ];

  // 可翻页推荐区组件
  function RecommendSection({ title, subtitle, list }: { title: string; subtitle?: string; list: { id: number; title: string; img: string }[] }) {
    const pageSize = 8;
    const [page, setPage] = useState(0);
    const totalPages = Math.ceil(list.length / pageSize);
    const canPrev = page > 0;
    const canNext = page < totalPages - 1;
    const handlePrev = () => setPage(p => Math.max(0, p - 1));
    const handleNext = () => setPage(p => Math.min(totalPages - 1, p + 1));
    return (
      <div style={{ background: '#f7f9fb', borderRadius: 12, margin: '32px 0 0 0', padding: '24px 0 0 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 32px' }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 20 }}>{title}</div>
            {subtitle && <div style={{ color: '#b0b8c4', fontSize: 14, marginTop: 2 }}>{subtitle}</div>}
          </div>
          <button style={{ background: 'none', border: 'none', color: '#888', fontSize: 15, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 2 }}>更多 <span style={{ fontSize: 18 }}>{'>'}</span></button>
        </div>
        <div style={{ position: 'relative', padding: '18px 32px 18px 32px' }}>
          {/* 翻页按钮 */}
          <button onClick={handlePrev} disabled={!canPrev} style={{ position: 'absolute', left: 0, top: '50%', transform: 'translateY(-50%)', zIndex: 2, background: '#fff', border: '1.5px solid #e3eaf1', borderRadius: 18, width: 36, height: 36, fontSize: 20, color: canPrev ? '#347aff' : '#ccc', cursor: canPrev ? 'pointer' : 'not-allowed', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{'<'}</button>
          <button onClick={handleNext} disabled={!canNext} style={{ position: 'absolute', right: 0, top: '50%', transform: 'translateY(-50%)', zIndex: 2, background: '#fff', border: '1.5px solid #e3eaf1', borderRadius: 18, width: 36, height: 36, fontSize: 20, color: canNext ? '#347aff' : '#ccc', cursor: canNext ? 'pointer' : 'not-allowed', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{'>'}</button>
          {/* 卡片区 */}
          <div style={{ overflow: 'hidden', width: '100%' }}>
            <div style={{ display: 'flex', gap: 18 }}>
              {list.slice(page * pageSize, (page + 1) * pageSize).map((item: { id: number; title: string; img: string }) => (
                <div key={item.id} style={{ minWidth: 150, maxWidth: 160, background: '#fff', borderRadius: 16, boxShadow: '0 2px 8px rgba(0,0,0,0.04)', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '0 0 12px 0', cursor: 'pointer', border: '1px solid #e3eaf1', transition: 'box-shadow 0.2s', position: 'relative' }}>
                  <img src={item.img} alt={item.title} loading="lazy" style={{ width: 150, height: 180, objectFit: 'cover', borderTopLeftRadius: 16, borderTopRightRadius: 16, background: '#f3f3f3' }} />
                  <div style={{ fontWeight: 600, fontSize: 15, color: '#222', marginTop: 10, textAlign: 'center', padding: '0 8px' }}>{item.title}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="home-container">
      {/* 导航栏 */}
      <Navbar onLoginClick={handleLoginClick} />

      {/* 主要内容区域 */}
      <main className="main-content">
        {/* 轮播图区域 - 包含搜索框和分类按钮 */}
        <div className="carousel-section">
          <Carousel 
            items={carouselItems}
            autoPlay={true}
            interval={4000}
            showIndicators={true}
            showArrows={true}
          />
          {/* 搜索框及热门弹窗包裹，绝对定位覆盖在轮播图上方 */}
          <div className="searchbar-pop-wrapper" style={{ position: 'absolute', left: 0, right: 0, top: 40, display: 'flex', flexDirection: 'column', alignItems: 'center', zIndex: 20, pointerEvents: 'none' }}>
            <div ref={searchBarRef} style={{ pointerEvents: 'auto', width: 'fit-content', minWidth: 320 }}>
              <SearchBar
                onSearch={handleSearch}
                onInputClick={() => setShowSearchPopup(true)}
                onInputChange={handleInputChange}
              />
            </div>
            {showSearchPopup && popStyle && (
              <div
                className="search-popup"
                style={{
                  position: 'absolute',
                  left: popStyle.left,
                  top: popStyle.top,
                  width: popStyle.width ? (typeof popStyle.width === 'number' ? popStyle.width + 250 : `calc(${popStyle.width} + 250px)`) : undefined,
                  zIndex: 200,
                  pointerEvents: 'auto',
                  background: '#fff',
                  borderRadius: 18,
                  boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
                  transform: 'translateX(-800px)'
                }}
              >
                  {inputValue ? (
                    // 搜索联想
                    <div className="suggestion-list" style={{ padding: '16px 0' }}>
                      {groupedSuggestionsState.map(group => (
                        <div key={group.group} style={{ marginBottom: 12 }}>
                          <div style={{ color: '#999', fontSize: 14, padding: '0 24px 8px 24px' }}>{group.group}</div>
                          {group.items.map(item => (
                            <div key={item} style={{ padding: '8px 24px', cursor: 'pointer' }}
                              onMouseEnter={e => e.currentTarget.style.backgroundColor = '#f5f5f5'}
                              onMouseLeave={e => e.currentTarget.style.backgroundColor = 'transparent'}
                            >{item}</div>
                          ))}
                        </div>
                      ))}
                    </div>
                  ) : (
                    // 热门搜索
                    <div>
                      <div className="hot-search-title" style={{ fontWeight: 700, fontSize: 20, padding: '24px 32px 0 32px', marginBottom: 8 }}>大家都在搜 <span style={{ color: 'red' }}>🔥</span></div>
                      <div className="hot-search-list" style={{ display: 'flex', flexDirection: 'column', gap: 24, padding: '24px 32px 32px 32px' }}>
                        {hotSearchRows.map((row) => (
                          <div key={row.left.title + row.right.title} style={{ display: 'flex', flexDirection: 'row', gap: 32 }}>
                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', background: row.left.bg, borderRadius: 14, minHeight: 72, padding: '10px 22px', gap: 18 }}>
                              <img src={row.left.img} alt={row.left.title} style={{ width: 56, height: 74, borderRadius: 8, objectFit: 'cover', background: '#eee', marginRight: 12 }} />
                              <span style={{ fontSize: 17, fontWeight: 500 }}>{row.left.title}</span>
                              {row.left.hot && <span className="hot-badge" style={{ background: '#ff4444', color: '#fff', fontSize: 13, fontWeight: 700, borderRadius: 6, padding: '2px 10px', marginLeft: 8 }}>Hot</span>}
                            </div>
                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', background: '#fff', borderRadius: 14, minHeight: 72, padding: '10px 22px', gap: 18, boxShadow: 'none' }}>
                              <img src={row.right.img} alt={row.right.title} style={{ width: 56, height: 74, borderRadius: 8, objectFit: 'cover', background: '#eee', marginRight: 12 }} />
                              <span style={{ fontSize: 17, fontWeight: 500 }}>{row.right.title}</span>
                              {row.right.hot && <span className="hot-badge" style={{ background: '#ff4444', color: '#fff', fontSize: 13, fontWeight: 700, borderRadius: 6, padding: '2px 10px', marginLeft: 8 }}>Hot</span>}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
            )}
          </div>
          {/* 分类按钮放在轮播图下方 */}
        </div>
        {/* 创作工具区域 */}
        <div style={{ background: '#eaf6fb', borderRadius: 12, margin: '32px 0 0 0', padding: '32px 32px 24px 32px', boxShadow: '0 2px 8px rgba(0,0,0,0.04)', width: '100%' }}>
          <div style={{ fontWeight: 700, fontSize: 24, marginBottom: 24 }}>创作工具</div>
          <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start', gap: 32 }}>
            {/* 左侧三张大卡片横向排列 */}
            <div style={{ display: 'flex', flexDirection: 'row', gap: 12, justifyContent: 'flex-start' }}>
              {creativeTools.slice(0, 3).map((tool: CreativeTool) => (
                <CreativeToolCard key={tool.title} tool={tool} />
              ))}
            </div>
            {/* 右侧8个小卡片整体顶端对齐，分两行四列 */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, justifyContent: 'flex-start', marginLeft: 30 }}>
              <div style={{ display: 'flex', gap: 12 }}>
                {creativeTools.slice(3, 7).map((tool: CreativeTool) => (
                  <CreativeToolCard key={tool.title} tool={tool} />
                ))}
              </div>
              <div style={{ display: 'flex', gap: 12 }}>
                {creativeTools.slice(7).map((tool: CreativeTool) => (
                  <CreativeToolCard key={tool.title} tool={tool} />
                ))}
              </div>
            </div>
          </div>
        </div>
        {/* 小红书区 */}
        <div style={{ background: '#f8fbfd', borderRadius: 12, margin: '24px 0 0 0', padding: '24px 32px 24px 32px', boxShadow: '0 2px 8px rgba(0,0,0,0.03)' }}>
          <TabsWithPages tabs={xhsTabs} data={xhsTabCards} pageSize={6} />
        </div>
        {/* 新品推荐区 */}
        <RecommendSection title="新品推荐" subtitle="模板上新，爆款来袭" list={newRecommendList} />
        {/* 热门推荐区 */}
        <RecommendSection title="热门推荐" subtitle="解锁设计灵感，爆款模板尽在掌握" list={hotRecommendList} />
      </main>

      {/* 登录弹框 */}
      <LoginModal 
        isOpen={isLoginModalOpen} 
        onClose={handleCloseLoginModal} 
      />
    </div>
  );
}

export default Index;
